package com.itobase.questionnaire.service.impl;

import com.itobase.questionnaire.dto.UpdateTagDTO;
import com.itobase.questionnaire.exception.BussinessException;
import com.itobase.questionnaire.exception.WrongParameterException;
import com.itobase.questionnaire.model.Tag;
import com.itobase.questionnaire.repository.TagFolderRepository;
import com.itobase.questionnaire.repository.TagRepository;
import com.itobase.questionnaire.service.ITagService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

/**
 * @author: lphu
 * @create: 2018-08-01 14:23
 * @description:
 */

@Service
public class TagService implements ITagService {

    @Autowired
    TagRepository tagRepository;

    @Autowired
    TagFolderRepository tagFolderRepository;


    /**
     * 新增标签
     * @param tag
     * @return
     */
    @Override
    public void addTag(Tag tag) {
        if (tag.getTagName()=="")
            throw new WrongParameterException("标签名不能为空");
        checkExist(tag.getTagName());
        tagRepository.insert(tag);
    }

    /**
     * 删除标签
     * @param tagId
     */
    @Override
    public void deleteTag(String tagId) {
        //todo 是否绑定人
        Optional.ofNullable(tagId)
                .orElseThrow(()->new WrongParameterException("传入参数错误"));
        tagRepository.delete(tagId);
    }

    /**
     * 更新标签
     * @param updateTagDTO
     */
    @Override
    public void updateTag(UpdateTagDTO updateTagDTO)
    {
        Tag tag  = Optional.ofNullable(tagRepository.findByTagName(updateTagDTO.getOldTagName()))
                .orElseThrow(() -> new WrongParameterException("传入参数错误"));
        if (updateTagDTO.getNewTagName()=="")
            throw new WrongParameterException("标签名不能为空");
        checkExist(updateTagDTO.getNewTagName());
        tag.setTagName(updateTagDTO.getNewTagName());
        tagRepository.save(tag);
    }

    @Override
    public List<Tag> getTagList(String tagFolderId) {
        return tagRepository.findByTagFolderId(tagFolderId);
    }


    /**
     * 校验标签名是否重复
     * @param tagName
     */
    private void checkExist(String tagName) {
        Tag existTag = tagRepository.findByTagName(tagName);
        if (existTag!=null)
            throw new WrongParameterException("标签名重复,请勿重复添加");
    }
}
